﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlimDX;
using SlimDX.Direct3D11;
using Vxl.Utils.Input;
using System.Windows.Forms;
using Vxl.Utils;

namespace Vxl.Cameras
{
    public class WASDCamera : BaseCamera
    {

        private float rotationSpeed = 0.1f;
        private float movementSpeed = 5.0f;
        private bool changed = false;

        public WASDCamera(Vector3 position, Vector3 lookAt) : base(position, lookAt)
        {

        }

        public override void Update(float dt)
        {
            HandleMouseMovement(dt);
            if (changed)
            {
                Rotation = Matrix.RotationYawPitchRoll(totalYaw, 0.0f, totalPitch);

                Forward = Vector3.TransformNormal(InitialForward, Rotation);
                Up = Vector3.TransformNormal(InitialUp, Rotation);
                Right = Vector3.TransformNormal(InitialRight, Rotation);
                LookAt = Position + Forward;
            }

            HandleKeyboard(dt);

            if (changed)
            {
                View = Matrix.LookAtLH(Position, Position + Forward, Up);
                changed = false;
            }
        }

        private void HandleKeyboard(float dt)
        {
            if (InputManager.input.IsKeyDown(Keys.W))
            {
                Position += Forward * dt * movementSpeed;
                changed = true;
            }
            if (InputManager.input.IsKeyDown(Keys.S))
            {
                Position -= Forward * dt * movementSpeed;
                changed = true;
            }
            if (InputManager.input.IsKeyDown(Keys.A))
            {
                Position -= Right * dt * movementSpeed;
                changed = true;
            }
            if (InputManager.input.IsKeyDown(Keys.D))
            {
                Position += Right * dt * movementSpeed;
                changed = true;
            }
        }

        private void HandleMouseMovement(float dt)
        {

            if (InputManager.input.MouseDelta.X != 0 || InputManager.input.MouseDelta.Y != 0)
            {
                changed = true;

                totalYaw += ((float)InputManager.input.MouseDelta.X / aspectRatio) * dt * rotationSpeed;
                totalPitch += ((float)InputManager.input.MouseDelta.Y / aspectRatio) * dt * rotationSpeed;

                if (totalYaw < 0.0f)
                    totalYaw += MathDeclarations.TWO_PI;
                else if (totalYaw > MathDeclarations.TWO_PI)
                    totalYaw -= MathDeclarations.TWO_PI;

                if (totalPitch < -MathDeclarations.PI_DIV_2 + 0.1f)
                    totalPitch = -MathDeclarations.PI_DIV_2 + 0.1f;
                else if (totalPitch > MathDeclarations.PI_DIV_2 - 0.1f)
                    totalPitch = MathDeclarations.PI_DIV_2 - 0.1f;
            }
        }

  }
}
